package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 根据id查询博客
     * @param id
     * @return
     */
    @Override
    public Result getBlogById(Long id) {
        Blog blog = blogMapper.getBlogAndUser(id);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 设置博客是否被当前用户点赞
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return;
        }
        // 当前用户id
        Long userId = user.getId();
        // 查询该博客是否被当前用户点赞
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId(), userId.toString());
        blog.setIsLike(score != null);
    }


    /**
     * 点赞或取消点赞博客
     * @param id
     */
    @Override
    public void likeBlog(Long id) {
        // 当前用户id
        Long userId = UserHolder.getUser().getId();
        // 当前用户是否点赞过该博客
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        if (score == null) {
            // 未点赞过，则数据库点赞数 +1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 在博客点赞用户的缓存中添加当前用户
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY + id, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 点赞过，则点赞数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 在缓存中删除当前用户
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY + id, userId.toString());
            }
        }
    }

    /**
     * 获取博客下点赞的用户
     * @param id
     * @return
     */
    @Override
    public List<UserDTO> getLikes(Long id) {
        // 根据博客id查询缓存中对应用户id top5
        Set<String> topIds = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if (topIds == null || topIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<Integer> userIds = topIds.stream().map(Integer::parseInt).collect(Collectors.toList());
        // 根据用户id查询数据库得到用户 select * from tb_user where id in (userIds) ORDER BY FIELD (id, userIds)
        String orderSQL = "ORDER BY FIELD(id, " + StrUtil.join(",", userIds) + ")";
        List<UserDTO> userDTOS = userService.query().in("id", userIds).last(orderSQL).list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 将用户列表返回
        return userDTOS;
    }

    /**
     * 保存博客，同时推送消息
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("保存博客失败！");
        }
        // 查询数据库获取当前用户的粉丝select * from tb_follow where follow_user_id =  user.getId()
        List<Follow> followUser = followService.query().eq("follow_user_id", user.getId()).list();
        // 获取粉丝id
        List<Long> followUserIds = followUser.stream().map(fans -> fans.getUserId()).collect(Collectors.toList());
        // 把博文id推送至粉丝的收件箱
        for (Long followUserId : followUserIds) {
            stringRedisTemplate.opsForZSet()
                    .add(FEED_KEY + followUserId, blog.getId().toString(), System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 推送关注的博主的博客
     * @param maxTime
     * @param offset
     * @return
     */
    @Override
    public Result BlogOfFollow(Long maxTime, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        String feedKey = FEED_KEY + userId;
        // 从缓存收件箱中取出数据 ZREVRANGEBYSCORE feed:userId 0 currentTime WITHSCORES LIMIT 0 2
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(feedKey, 0, maxTime, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 博客id集合
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        // 解析
        Double minTime = 0D;
        Integer os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 获取博客id
            blogIds.add(Long.parseLong(typedTuple.getValue()));
            // 计算得到最小时间和偏移量
            if (minTime == typedTuple.getScore()) {
                os++;
            } else {
                minTime = typedTuple.getScore();
                os = 1;
            }
        }

        // 根据博客id集合查询博客 select * from blog where id in (blogIds) ORDER BY FILED(ID, blogIds)
        String orderSQL = "ORDER BY FIELD(id, " + StrUtil.join(",", blogIds) + ")";
        List<Blog> blogs = query().in("id", blogIds).last(orderSQL).list();
        // 添加字段信息
        blogs.forEach(new Consumer<Blog>() {
            @Override
            public void accept(Blog blog) {
                isBlogLiked(blog);
                Long id = blog.getUserId();
                User user = userService.getById(id);
                blog.setName(user.getNickName());
                blog.setIcon(user.getIcon());
            }
        });

        // 封装返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime.longValue());
        return Result.ok(scrollResult);
    }

}
